import * as React from 'react';
import {
    Modal
  } from 'react-bootstrap';
import * as cx from 'classnames';
import { fetch, filterDate } from '../../../renderers/util';
import * as moment from 'moment';
import {render} from '../../../renderers/factory';

const plans = [
    {
        code: '001',
        price: 2,
        title: '中国人寿财险志愿者保障 A款',
        description: '意外伤害20万元，意外、急重症医疗5000元',
        detailLink: 'http://wx.zybailian.com/index.php/Home/Item/view/Id/996.html'
    },
    {
        code: '002',
        price: 5,
        title: '中国人寿财险志愿者保险 B款',
        description: '意外伤害20万元，意外、急重症医疗2万元，导致第三方财产损失或者伤亡2万元',
        detailLink: 'http://wx.zybailian.com/index.php/Home/Item/view/Id/997.html'
    },
    {
        code: '003',
        price: 15,
        title: '中国人寿财险志愿者保险 C款',
        description: '意外伤害50万元，意外、急重症医疗5万元，导致财产损失或伤亡5万元',
        detailLink: 'http://wx.zybailian.com/index.php/Home/Item/view/Id/998.html'
    },
    {
        code: '004',
        price: 280,
        title: '中国人寿财险志愿者组织保险 D款',
        description: '意外身故、伤残50万元，意外医疗（门急诊、住院5万元）',
        detailLink: 'http://wx.zybailian.com/index.php/Home/Item/view/Id/999.html'
    }
];


export default class BuySafe extends React.Component {
    constructor(props) {
        super(props);

        this.open = this.open.bind(this);
        this.close = this.close.bind(this);
        this.choose = this.choose.bind(this);
        this.nextStep = this.nextStep.bind(this);
        this.state = {
            step: 1,
            openedPlan: null,
            selectedCode: ''
        };
    }

    choose(code) {
        this.setState({
            selectedCode: code
        });
    }

    nextStep() {
        if (!this.state.selectedCode) {
            return;
        }

        this.setState({
            step: 2
        });
    }

    open(plan) {
        this.setState({
            openedPlan: plan
        });
    }

    close() {
        this.setState({
            openedPlan: null
        });
    }

    render() {
        const {
            params
        } = this.props;

        return (
            <div>
                <div className="bg-light b-b wrapper"><h1 className="m-n font-thin h3 text-black">保险购买</h1></div>
                {this.state.step === 1 ? (
                    <div className="wrapper-md">
                        <h3 className="font-thin m-t-none m-b">请选择保险方案</h3>
                        <div className="row">
                            {plans.map((plan, index) => (
                                <div className="col-xs-3" key={index}>
                                    <div className={cx('panel', plan.code === this.state.selectedCode ? 'bg-info' : 'bg-default' )} onClick={() => this.choose(plan.code)}>
                                        <div className={'panel-heading text-center no-border'}>
                                            <h2 className="m-t-none m-b-none">
                                                <sup className="pos-rlt" style={{top:-22}}>￥</sup>
                                                <span className="text-2x text-lt">{plan.price}</span>
                                            </h2>
                                        </div>
                                        <div className="panel-body">
                                            <h4>{plan.title}</h4>
                                            <p>{plan.description}</p>
                                            <div className="text-right">
                                                <a onClick={this.open.bind(this, plan)}>查看详情</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                        <div className="clearfix">
                            <button onClick={this.nextStep} className="btn btn-info pull-right" disabled={!this.state.selectedCode}>下一步</button>
                        </div>
                    </div>
                ) : (
                    <OrderForm {...this.props} code={this.state.selectedCode} projectId={params.id}  />
                )}
                {this.state.openedPlan ? (
                    <Modal
                        onHide={this.close}
                        show
                    >
                        <Modal.Header closeButton>
                            <Modal.Title>查看详情</Modal.Title>
                        </Modal.Header>

                        <div className="wrapper">
                            <div className="text-center">
                                <img src={`/qrcode?size=250&data=${encodeURIComponent(this.state.openedPlan.detailLink)}`} />
                            </div>
                        </div>
                    </Modal>
                ) : null}
            </div>
        );
    }
}


class OrderForm extends React.Component {

    form = null;

    constructor(props) {
        super(props);

        this.state = {
            product_code: props.code,
            activity_code: '',
            activity_id: '',
            activity_name: '',
            start_date: '',
            end_date: '',
            m_type: 1,
            m_name: '',
            m_cardno: '',
            m_email: '',
            m_mobile: '',
            token: '',
            volunteers: [],
            selected: []
        };

        this.check = this.check.bind(this);
        this.checkAll = this.checkAll.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.formRef = this.formRef.bind(this);
    }

    componentDidMount() {
        const {
            projectId
        } = this.props;

        fetch(`/api/project/buy-safe/${projectId}`).then(ret => this.setState({
            ...ret.data,
            start_date: ret.data.start_date || '+1day',
            end_date: ret.data.end_date || filterDate('+2day').hours(23).minutes(59).format('X')
        }));
    }


    checkAll() {
        if (this.state.selected.length && this.state.selected.length ===  this.state.volunteers.length) {
            this.setState({
                selected: []
            });
        } else {
            this.setState({
                selected: this.state.volunteers.concat()
            });
        }
    }

    check(volunteer) {
        const arr = this.state.selected.concat();
        const idx = arr.indexOf(volunteer);

        if (~idx) {
            arr.splice(idx, 1);
        } else {
            arr.push(volunteer)
        }

        this.setState({
            selected: arr
        });
    }

    formRef(ref) {
        this.form = ref;
    }

    handleChange(values) {
        let start_date = values.start_date;
        let end_date = values.end_date;
        let m_name = values.m_name;
        let m_cardno = values.m_cardno;

        // if (/^\d{4}$/.test(start_date) || /^\d{4}$/.test(end_date)) {
        //     return;
        // }

        if (end_date) {
            end_date = filterDate(end_date).hours(23).minutes(59).format('X');
        }

        if (start_date) {
            let date = filterDate(start_date);
            if (date.format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')) {
                date.hours(moment().hours() + 1)
                date.minutes(0);
                start_date = date.format('X');
            } else {
                date.hours(0);
                date.minutes(0);
                start_date = date.format('X');
            }
        }

        if (values.m_type !== this.state.m_type) {
            m_name = '';
            m_cardno = '';
        }

        this.setState({
            ...values,
            start_date,
            end_date,
            m_name,
            m_cardno
        })
    }

    handleSubmit(values) {
        this.setState({
            ...values
        }, () => this.form.submit());
    }

    render() {
        return (
            <div className="wrapper-md">
                {!this.state.activity_id ? (
                    <div className="text-center wrapper">
                        <i className="fa fa-spinner fa-spin fa-3x fa-fw" />
                    </div>
                ) : <div className="bg-white">
                {render('page', {
                    type: 'page',
                    title: '',
                    bodyClassName: '',
                    body: {
                        title: null,
                        panelClassName: 'no-border no-shadow',
                        type: 'form',
                        onSubmit: this.handleSubmit,
                        onFormChange: this.handleChange,
                        data: this.state,
                        actions: [
                            {
                                label: '前往购买',
                                type: 'submit',
                                level: 'info',
                                disabled: !this.state.selected.length
                            }
                        ],
                        fieldSet: [
                            {
                                title: '请选择参保时间',
                                subTitle: '提示：当天活动开始后，不能购买当日的保险',
                                controls: [
                                    {
                                        type: 'date',
                                        label: '保单开始时间',
                                        name: 'start_date',
                                        value: '+1day',
                                        minDate: 'today',
                                        maxDate: '${end_date}',
                                        inputFormat: 'YYYY-MM-DD HH:mm',
                                        width: 280
                                    },

                                    {
                                        type: 'date',
                                        label: '保单结束时间',
                                        name: 'end_date',
                                        value: '+2day',
                                        minDate: '${start_date}',
                                        inputFormat: 'YYYY-MM-DD HH:mm',
                                        width: 280
                                    }
                                ]
                            },

                            {
                                title: '请选择投保人信息',
                                className: 'm-t-lg',
                                controls: [
                                    {
                                        label: false,
                                        name: 'm_type',
                                        type: 'button-group',
                                        btnActiveClassName: 'btn-info active',
                                        value: 1,
                                        options: [
                                            {
                                                label: '个人购买',
                                                value: 1
                                            },
                                            {
                                                label: '团队购买',
                                                value: 2
                                            }
                                        ]
                                    },

                                    {
                                        type: 'text',
                                        label: '姓名',
                                        required: true,
                                        name: 'm_name',
                                        visibleOn: 'data.m_type == 1',
                                        width: 240,
                                        labelClassName: 'w-xs',
                                        inline: true
                                    },

                                    {
                                        type: 'text',
                                        label: '身份证号',
                                        validations: 'isID',
                                        required: true,
                                        name: 'm_cardno',
                                        visibleOn: 'data.m_type == 1',
                                        width: 240,
                                        labelClassName: 'w-xs',
                                        inline: true
                                    },

                                    {
                                        type: 'text',
                                        label: '团队/企业名称',
                                        required: true,
                                        name: 'm_name',
                                        visibleOn: 'data.m_type == 2',
                                        width: 240,
                                        labelClassName: 'w-xs',
                                        inline: true
                                    },

                                    {
                                        type: 'text',
                                        label: '纳税人识别号',
                                        required: true,
                                        name: 'm_cardno',
                                        visibleOn: 'data.m_type == 2',
                                        width: 240,
                                        labelClassName: 'w-xs',
                                        inline: true
                                    },

                                    {
                                        type: 'text',
                                        label: '联系电话',
                                        required: true,
                                        name: 'm_mobile',
                                        validations: 'isPhone',
                                        width: 240,
                                        labelClassName: 'w-xs',
                                        inline: true
                                    },

                                    {
                                        type: 'email',
                                        label: '邮箱',
                                        required: true,
                                        name: 'm_email',
                                        width: 240,
                                        labelClassName: 'w-xs',
                                        inline: true
                                    },

                                    {
                                        name: 'desc',
                                        className: 'm-t-lg',
                                        type: 'tpl',
                                        tpl: '<p>保单以及发票将会发送到您填写的邮箱中</p><p>个人购买，发票抬头为个人姓名</p><p>团队购买，发票抬头为团队名称</p>'
                                    }
                                ]
                            },

                            {
                                title: '请选择被投保人',
                                className: 'm-t-lg',
                                controls: [
                                    {
                                        children: () => (this.state.volunteers.length ? (
                                            <div className="table-responsive bg-white b-a m-t-md">
                                                {/* {this.state.selected.map((volunteer, index) => (
                                                    <div key={index}>
                                                        <input type="hidden" name={`info[${index}][c_name]`} value={volunteer.c_name} />
                                                        <input type="hidden" name={`info[${index}][c_mobile]`} value={volunteer.c_mobile} />
                                                        <input type="hidden" name={`info[${index}][c_cardno]`} value={volunteer.c_cardno} />
                                                    </div>
                                                ))} */}

                                                <table className="table table-striped m-b-none">
                                                    <thead>
                                                        <tr>
                                                            <th style={{width: 40}}><label className="i-checks m-b-none"><input  checked={this.state.selected.length === this.state.volunteers.length && this.state.volunteers.length} onChange={this.checkAll.bind(this)}  type="checkbox" value="on" /><i /></label></th>
                                                            <th>姓名</th>
                                                            <th>联系电话</th>
                                                            <th>身份证号</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {this.state.volunteers.map((volunteer, index) => (
                                                            <tr key={index}>
                                                                <td><label className="i-checks m-b-none"><input checked={!!~this.state.selected.indexOf(volunteer)} onChange={this.check.bind(this, volunteer)} type="checkbox" value="on" /><i /></label></td>
                                                                <td>{volunteer.c_name}</td>

                                                                <td>{volunteer.c_mobile}</td>
                                                                <td>{volunteer.c_cardno}</td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        ) : (
                                            <div className="text-muted">
                                                当前还没有志愿者加入该项目，不能完成购买。
                                            </div>
                                        ))
                                    }
                                ]
                            }
                        ]
                    }
                }, this.props)}
            </div>}

                <form ref={this.formRef} method="post" action="http://www.zybailian.com:8999/index.php?s=/insurance/home/activityZyz/order">
                    <input type="hidden" name="activity_code" value={this.state.activity_code || this.state.activity_id} />
                    <input type="hidden" name="token" value={this.state.token} />
                    <input type="hidden" name="product_code" value={this.state.product_code} />
                    <input type="hidden" name="activity_name" value={this.state.activity_name} />
                    <input type="hidden" name="m_type" value={this.state.m_type} />
                    <input type="hidden" name="m_name" value={this.state.m_name} />
                    <input type="hidden" name="m_cardno" value={this.state.m_cardno} />
                    <input type="hidden" name="m_mobile" value={this.state.m_mobile} />
                    <input type="hidden" name="m_email" value={this.state.m_email} />
                    <input type="hidden" name="start_date" value={moment(this.state.start_date, 'X').format('YYYY-MM-DD HH:mm')} />
                    <input type="hidden" name="end_date" value={moment(this.state.end_date, 'X').format('YYYY-MM-DD HH:mm')} />
                    <input type="hidden" name="info" value={JSON.stringify(this.state.selected)} />
                </form>

            </div>
        );
    }
}
